//
//  Session.m
//  SHPE Conference Companion
//
//  Created by Richard Kirk on 3/25/11.
//  Copyright (c) 2011 __MyCompanyName__. All rights reserved.
//

#import "Session.h"
#import "Conference.h"
#import "Speaker.h"


@implementation Session
@dynamic id;
@dynamic title;
@dynamic startTime;
@dynamic endTime;
@dynamic desc;
@dynamic room;
@dynamic type;
@dynamic tracks;
@dynamic conference;
@dynamic venue;
@dynamic speakers;
@synthesize parent;
@synthesize xmlParser, xmlStringBuilder, dateFormatter;



-(id)initWithParser:(NSXMLParser *)parser attributeDict:(NSDictionary *)attributes parent:(id)parentObject
{   
    
    [super initWithEntity:[NSEntityDescription entityForName:@"Session" inManagedObjectContext:[self managedObjectContext] ] insertIntoManagedObjectContext:[self managedObjectContext]];
    
    [parser setDelegate:self];
    [self setParent:parentObject];
    
    dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"MM/DD/YYYY hh:mm:ss"];
    
    self.id = [NSNumber numberWithInt:[[attributes objectForKey:@"id"] intValue]];
    self.title = [NSString stringWithString:[attributes objectForKey:@"title"]];    
    return self;

}

-(id)initWithSessionId:(int)sessionId
{
    
    [super init];
    
    xmlParser = [NSXMLParser alloc];
    xmlParser.delegate = self;
    
    [xmlParser initWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://openshpe.staging.shpe.org/conference/v1/session/%d", sessionId]]];    
    
    if (xmlParser){
        [xmlParser parse];
    }
    
    
    return self;
}

-(NSString *)description
{
    NSMutableString * description = [[[NSMutableString alloc]init] autorelease];
    
    
        [description appendString:[NSString stringWithFormat:@"\n-------Session %@-------\n",self.title]];
    
   [description appendString:[NSString stringWithFormat:@"\nSessionid : %@\nTitle : %@\nStart Time : %@\nEnd Time : %@\nDescription : %@\nRoom Num : %@\n", self.id, self.title, self.startTime, self.endTime, self.desc, self.room]];
    
[description appendString:[NSString stringWithFormat:@"\n-------%@ Venue-------\n",self.title]];
    [description appendString:[NSString stringWithFormat:@"%@",self.venue ]]; 
   
    
    [description appendString:[NSString stringWithFormat:@"\n-------%@ Session Types-------\n", self.title]];
  
    [description appendString:[NSString stringWithFormat:@"--------------------------%@",self.type ]]; 

     [description appendString:[NSString stringWithFormat:@"\n-------%@ Tracks-------\n", self.title]];
    for (Track * item in self.tracks ) {
        [description appendString:[NSString stringWithFormat:@"--------------------------%@",item ]]; 
    }
    [description appendString:[NSString stringWithFormat:@"\n-------%@ Speakers-------\n", self.title]];
    for (Speaker * item in self.speakers ) {
        [description appendString:[NSString stringWithFormat:@"--------------------------%@",item ]]; 
    }

    
    return description;
    
}




- (void)addTracksObject:(NSManagedObject *)value {    
    NSSet *changedObjects = [[NSSet alloc] initWithObjects:&value count:1];
    [self willChangeValueForKey:@"tracks" withSetMutation:NSKeyValueUnionSetMutation usingObjects:changedObjects];
    [[self primitiveValueForKey:@"tracks"] addObject:value];
    [self didChangeValueForKey:@"tracks" withSetMutation:NSKeyValueUnionSetMutation usingObjects:changedObjects];
    [changedObjects release];
}

- (void)removeTracksObject:(NSManagedObject *)value {
    NSSet *changedObjects = [[NSSet alloc] initWithObjects:&value count:1];
    [self willChangeValueForKey:@"tracks" withSetMutation:NSKeyValueMinusSetMutation usingObjects:changedObjects];
    [[self primitiveValueForKey:@"tracks"] removeObject:value];
    [self didChangeValueForKey:@"tracks" withSetMutation:NSKeyValueMinusSetMutation usingObjects:changedObjects];
    [changedObjects release];
}

- (void)addTracks:(NSSet *)value {    
    [self willChangeValueForKey:@"tracks" withSetMutation:NSKeyValueUnionSetMutation usingObjects:value];
    [[self primitiveValueForKey:@"tracks"] unionSet:value];
    [self didChangeValueForKey:@"tracks" withSetMutation:NSKeyValueUnionSetMutation usingObjects:value];
}

- (void)removeTracks:(NSSet *)value {
    [self willChangeValueForKey:@"tracks" withSetMutation:NSKeyValueMinusSetMutation usingObjects:value];
    [[self primitiveValueForKey:@"tracks"] minusSet:value];
    [self didChangeValueForKey:@"tracks" withSetMutation:NSKeyValueMinusSetMutation usingObjects:value];
}




- (void)addSpeakersObject:(Speaker *)value {    
    NSSet *changedObjects = [[NSSet alloc] initWithObjects:&value count:1];
    [self willChangeValueForKey:@"speakers" withSetMutation:NSKeyValueUnionSetMutation usingObjects:changedObjects];
    [[self primitiveValueForKey:@"speakers"] addObject:value];
    [self didChangeValueForKey:@"speakers" withSetMutation:NSKeyValueUnionSetMutation usingObjects:changedObjects];
    [changedObjects release];
}

- (void)removeSpeakersObject:(Speaker *)value {
    NSSet *changedObjects = [[NSSet alloc] initWithObjects:&value count:1];
    [self willChangeValueForKey:@"speakers" withSetMutation:NSKeyValueMinusSetMutation usingObjects:changedObjects];
    [[self primitiveValueForKey:@"speakers"] removeObject:value];
    [self didChangeValueForKey:@"speakers" withSetMutation:NSKeyValueMinusSetMutation usingObjects:changedObjects];
    [changedObjects release];
}

- (void)addSpeakers:(NSSet *)value {    
    [self willChangeValueForKey:@"speakers" withSetMutation:NSKeyValueUnionSetMutation usingObjects:value];
    [[self primitiveValueForKey:@"speakers"] unionSet:value];
    [self didChangeValueForKey:@"speakers" withSetMutation:NSKeyValueUnionSetMutation usingObjects:value];
}

- (void)removeSpeakers:(NSSet *)value {
    [self willChangeValueForKey:@"speakers" withSetMutation:NSKeyValueMinusSetMutation usingObjects:value];
    [[self primitiveValueForKey:@"speakers"] minusSet:value];
    [self didChangeValueForKey:@"speakers" withSetMutation:NSKeyValueMinusSetMutation usingObjects:value];
}









-(void)parserDidStartDocument:(NSXMLParser *)parser
{
    dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"MM/DD/YYYY hh:mm:ss"];
    
    
}


- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict 
{
    
    if ( ( [elementName isEqualToString:@"conference-session"] )) {
        self.id = [NSNumber numberWithInt:[[attributeDict objectForKey:@"id"] intValue]];
        self.title = [NSString stringWithString:[attributeDict objectForKey:@"title"]];
        return;
    }
    
    

    
    if ( ( [elementName isEqualToString:@"location"] )) {
        NSFetchRequest *venueRequest = [[[NSFetchRequest alloc] init] autorelease];
        [venueRequest setEntity:[NSEntityDescription entityForName:@"Venue" inManagedObjectContext:[self managedObjectContext]]];
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(id = %d)",[[attributeDict objectForKey:@"venue-id"] intValue]];
        
        [venueRequest setPredicate:predicate];
        [venueRequest setSortDescriptors:nil];
        
        NSArray *venueObjectArray = [[self managedObjectContext] executeFetchRequest:venueRequest error:nil];
       if([venueObjectArray lastObject])
       {
           [self setVenue:[venueObjectArray lastObject]];
       }
        else 
            NSLog(@"Venue location request returned nil\n",nil);
        
        
        
        
      
        if([attributeDict objectForKey:@"room"])
            self.room = [NSString stringWithString:[attributeDict objectForKey:@"room"]];
        
        return;
    }
    
    if ( ( [elementName isEqualToString:@"session-type"] )) {
    
        NSFetchRequest *sessionTypeRequest = [[[NSFetchRequest alloc] init] autorelease];
        [sessionTypeRequest setEntity:[NSEntityDescription entityForName:@"SessionType" inManagedObjectContext:[self managedObjectContext]]];
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(id = %d)",[[attributeDict objectForKey:@"id"] intValue]];
        
        [sessionTypeRequest setPredicate:predicate];
        [sessionTypeRequest setSortDescriptors:nil];
        
        NSArray *sessionTypeObjectArray = [[self managedObjectContext] executeFetchRequest:sessionTypeRequest error:nil];
        if([sessionTypeObjectArray lastObject])
        {
            [self setType:[sessionTypeObjectArray lastObject]];
        }
        else 
            NSLog(@"Venue SessionType request returned nil\n",nil);
        return;
    }
    if ( ( [elementName isEqualToString:@"track"] )) {
        
        NSFetchRequest *trackRequest = [[[NSFetchRequest alloc] init] autorelease];
        [trackRequest setEntity:[NSEntityDescription entityForName:@"Track" inManagedObjectContext:[self managedObjectContext]]];
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(id = %d)",[[attributeDict objectForKey:@"id"] intValue]];
        
        [trackRequest setPredicate:predicate];
        [trackRequest setSortDescriptors:nil];
        
        NSArray *trackObjectArray = [[self managedObjectContext] executeFetchRequest:trackRequest error:nil];
        if([trackObjectArray lastObject])
        {
            [self addTracksObject:[trackObjectArray lastObject]];
        }
        else 
            NSLog(@"Tracks request returned nil\n",nil);
        return;
    }
    if ( ( [elementName isEqualToString:@"Speaker"] )) {
        
        NSFetchRequest *speakerRequest = [[[NSFetchRequest alloc] init] autorelease];
        [speakerRequest setEntity:[NSEntityDescription entityForName:@"Speaker" inManagedObjectContext:[self managedObjectContext]]];
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(id = %d)",[[attributeDict objectForKey:@"id"] intValue]];
        
        [speakerRequest setPredicate:predicate];
        [speakerRequest setSortDescriptors:nil];
        
        NSArray *speakerObjectArray = [[self managedObjectContext] executeFetchRequest:speakerRequest error:nil];
        if([speakerObjectArray lastObject])
        {
            [self addTracksObject:[speakerObjectArray lastObject]];
        }
        else 
            NSLog(@"Speaker request returned nil\n",nil);
        return;
    }

    
    if ( ( [elementName isEqualToString:@"conference"] )) {
        
        
        /* Need to link the Conference here */
        /*
         self.conference = [NSNumber numberWithInt:[[attributeDict objectForKey:@"id"] intValue]];
         
         */
        return;
    }

}



- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string 
{   string = [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    string = [string stringByReplacingOccurrencesOfString:@"&amp;" withString:@" & "];
    string = [string stringByReplacingOccurrencesOfString:@"&lt;" withString:@"<"];
    string = [string stringByReplacingOccurrencesOfString:@"&gt;" withString:@">"];
    if (!xmlStringBuilder) {
        xmlStringBuilder = [[NSMutableString alloc] initWithCapacity:100];
    }
    
    [xmlStringBuilder appendString:string];
    
    
}

-(void)parser:(NSXMLParser *)parser foundIgnorableWhitespace:(NSString *)whitespaceString
{    
    
        //Didnt need this 
    /**
     
     NSLog(@"\nfound ignoreable whitespace: whitespace string: \"%@\"\n", whitespaceString);
     if (!xmlStringBuilder) {
     xmlStringBuilder = [[NSMutableString alloc] initWithCapacity:100];
     
     }
     //   if (whitespaceString != @"\n")
     // [xmlStringBuilder appendString:whitespaceString];
     
     */
    
}


- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
    
        // ignore root and empty elements
    if (( [elementName isEqualToString:@"tracks"] ) ||
        ( [elementName isEqualToString:@"speaker"] ) ||
        ( [elementName isEqualToString:@"speakers"] ))
            return;
    
    else if ( [elementName isEqualToString:@"conference-session"]) {
        [parser setDelegate:parent];
        xmlStringBuilder = nil;
        [dateFormatter release];
        return;
    }
    
    else if( [elementName isEqualToString:@"start-time"] ) {
        
        self.startTime = [dateFormatter dateFromString:xmlStringBuilder];
        
    }
    
    else if( [elementName isEqualToString:@"end-time"] ) {
        
        self.endTime = [dateFormatter dateFromString:xmlStringBuilder];
        
    }
    
    else if( [elementName isEqualToString:@"description"] ) {
        
        self.desc =[NSString stringWithString:xmlStringBuilder];
        
    }
    else if( [elementName isEqualToString:@"material"] ) {
        

    }
    
    
    xmlStringBuilder = nil;
    
    
    
}



-(void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError
{
    
    NSLog(@"XML ERROR :\n%@\n",[parseError description]);
    
    UIAlertView *parserAlert = [[UIAlertView alloc]init];
    
    
    [parserAlert setTitle:@"Parsing Error!"];
    
    [parserAlert setMessage:[NSString stringWithFormat:@"Error %i, Description: %@, Line: %i, Column: %i", 
                             [parseError code], 
                             [parseError localizedDescription], 
                             [parser lineNumber], 
                             [parser columnNumber]]];
    
    [parserAlert addButtonWithTitle:@"OK"];
    [parserAlert show];
    [parserAlert release];
    
    
    
}

-(void)parserDidEndDocument:(NSXMLParser *)parser
{
    
    [dateFormatter release];
}


@end


